package com.lxd.kyvideo.controller.frontend;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.lxd.kyvideo.common.ApiResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Value("${web.windows.upload-path}")
    private String windowsSavePath;


    @Value("${web.linux.upload-path}")
    private String linuxSavePath;


    @Resource
    private Environment env;


    @PostMapping("/setAvatar")
    public ApiResult uploadAvatar(
            @RequestParam(required = false,value = "upFile") MultipartFile upFile){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        if(upFile.isEmpty()) {
            return ApiResult.fail("您未选择任何文件！");
        }
        else {
            // 获取客户端上传的文件名
            String originalFileName = upFile.getOriginalFilename();
            String fileSuffix = FileUtil.extName(originalFileName);
            String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + fileSuffix;
            //限制文件类型
            if (! ( fileSuffix.equals("jpg") || fileSuffix.equals("png") )) {
                return ApiResult.fail("仅支持上传.jpg、.png图片格式！");
            }
            // 获取操作系统名称
            String osName = env.getProperty("os.name");
            File saveFile  = null;
            String format = sdf.format(new Date());
            if(osName.contains("Windows")) {
                 saveFile = new File(windowsSavePath + format);
            }
            else {
                saveFile = new File(linuxSavePath + format);
            }
            // 如果服务器保存文件目录不存在，则创建
            if(saveFile != null && !saveFile.exists()) {
                saveFile.mkdirs();
            }
            try {
                upFile.transferTo(new File(saveFile,newFileName));
                String imgUrl = "/resource/"+ format + newFileName; // 客户端访问头像路径，也就是存储在数据库中路径
                return ApiResult.ok(imgUrl,"头像上传成功！");
            } catch (IOException e) {
                return ApiResult.fail("上传头像失败！");
            }
        }
    }
}
